import { createApp } from 'vue';
import { router } from './router';
import store from './store';
import App from './App.vue';
const app = createApp(App);

// 角色权限，动态路由
const whiteList = ['/login', '/404'];
let pageRefresh = true;
router.beforeEach(async (to, from) => {
    // 如果是login或者404页面直接跳转过去
    if (whiteList.indexOf(to.path) !== -1) {
        if (to.path == '/login') {
            pageRefresh = true;
        }
        return true;
    }
    // 获取token，如果用户没登录，则跳转登录页面
    const token = store.getters.token;
    if (!token) {
        router.push({
            path: 'login',
            query: {
                redirect: to.path,
            },
        });
    } else {
        //如果为true说明已添加过直接跳过
        if (!pageRefresh) {
            return true;
        } else {
            //后端获取动态路由
            await store
                .dispatch('permission/generateRoutes')
                .then((res: any) => {
                    console.log(router.getRoutes());
                    // 没有子路由时则回首页
                    if (res && to.matched.length === 0) {
                        router.push(to.fullPath);
                    }
                });
            pageRefresh = false;
        }
    }
});

app.use(router).use(store).mount('#app');
